/**
 * 
 */
package org.mspring.mlog.support.resolver;

import java.util.Map;

import org.mspring.mlog.common.SpaceConst;
import org.mspring.mlog.core.ServiceFactory;
import org.mspring.mlog.entity.security.User;
import org.mspring.platform.exception.BusinessException;
import org.mspring.platform.utils.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.servlet.HandlerMapping;

/**
 * @author Gao Youbo
 * @since 2013-6-12
 * @Description 处理UCenter所需的通用函数
 * @TODO
 */
public class SpaceUserWebArgumentResolver implements WebArgumentResolver {
    @SuppressWarnings("unchecked")
    @Override
    public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest nativeWebRequest) throws Exception {
        // TODO Auto-generated method stub
        SpaceUser spaceUser = methodParameter.getParameterAnnotation(SpaceUser.class);
        // 如果没有添加 @SpaceUser注解，那么不解析参数
        if (spaceUser == null) {
            return WebArgumentResolver.UNRESOLVED;
        }
        // 如果参数类型不是User及其衍生类，那么不解析参数
        if (!methodParameter.getParameterType().isAssignableFrom(User.class)) {
            throw new BusinessException("解析阐述@SpaceUser失败，需要参数类型：" + User.class + "，实际参数类型：" + methodParameter.getParameterType() + "；参数名称：" + methodParameter.getParameterName());
            // return WebArgumentResolver.UNRESOLVED;
        }

        String pathVariableName = spaceUser.pathVariable();
        Map<String, String> uriTemplateVars = (Map<String, String>) nativeWebRequest.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
        String username = (uriTemplateVars != null) ? uriTemplateVars.get(pathVariableName) : null;

        if (StringUtils.isBlank(username)) {
            return WebArgumentResolver.UNRESOLVED;
        }
        User user = ServiceFactory.getUserService().getUserByName(username);
        if (user != null) {
            nativeWebRequest.setAttribute(SpaceConst.SPACE_USER, user, RequestAttributes.SCOPE_REQUEST);
            nativeWebRequest.setAttribute(SpaceConst.SPACE_URL, nativeWebRequest.getContextPath() + "/u/" + user.getName(), RequestAttributes.SCOPE_REQUEST);
            return user;
        }
        return WebArgumentResolver.UNRESOLVED;
    }

}
